package com.sh.aspects;

import com.sh.bean.CartItem;
import com.sh.bean.MessageBean;
import com.sh.utils.JmsMessageProducer;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

@Aspect
@Component
//@Order(10)
public class ResorderEmailAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JmsMessageProducer jmsMessageProducer;


    @Pointcut("execution(* com.sh.web.controller.CartController.confirmOrder(..))")
    private void confirmOrder() {

    }

    @Pointcut("confirmOrder()")
    private void all() {
    }


    @Before("all()")
    public void sendEmail(JoinPoint joinPoint) throws IOException {
        System.out.println(joinPoint);  // execution(ResponseResult com.sh.web.controller.CartController.confirmOrder(HttpServletRequest))
        Object[] args = joinPoint.getArgs();
        // 拿到请求体
        HttpServletRequest request = null;
        if (args!= null && args.length > 0 && args[0] instanceof HttpServletRequest) {
            request = (HttpServletRequest) args[0];
        }
/*        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Map<String, Object> useClaims = (Map<String, Object>)request.getAttribute("userClaims");
        String userid = useClaims.get("userid").toString();*/
        // userClaims
        Map<String, Object> useClaims = (Map<String, Object>)request.getAttribute("userClaims");
        String userid = useClaims.get("userid").toString();  // 用户id
        Map<String, CartItem> cart = (Map<String, CartItem>)this.redisTemplate.opsForValue().get("cart:"+userid);

        // 请求体内容
        BufferedReader reader = request.getReader();
        StringBuilder requestBody = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            requestBody.append(line);
        }
        System.out.println("请求体内容：" + requestBody.toString());

        // 发送邮件  其实是发到消息中间件里面
        String username = (String) useClaims.get("username");  // 用户名
        MessageBean messageBean = new MessageBean();
        messageBean.setUsername(username);
        messageBean.setUserid(userid);
        messageBean.setCart(cart);
        jmsMessageProducer.sendMessage(messageBean);
    }
}
